/*
 * UpStoneGachyaResource.cpp
 *
 *  Created on: 2014. 3. 3.
 *      Author: mega
 */

#include <algorithm>
#include <Database/Static.h>
#include <Toolkit/Str.h>
#include "UpStoneGachyaResource.h"

#include "../macro.h"

namespace ProjectZ { namespace NResource {

UpStoneGachyaResource::UpStoneGachyaResource()
{

}

UpStoneGachyaResource::~UpStoneGachyaResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](UPSTONEGACHYATREE::value_type & pair) {
		delete pair.second;
	} );
}

void
UpStoneGachyaResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), [&](UPSTONEGACHYATREE::value_type & pair) {
		delete pair.second;
	} );
	clsFlyTree.clear();
}

bool
UpStoneGachyaResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_upstone_gachya");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		Flyweight * pFly = new Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_IDX >> pFly->_RATE1 >> pFly->_RATE2
				>> pFly->_RATE3 >> pFly->_RATE4 >> pFly->_RATE5 >> pFly->_RATE6
				>> pFly->_RATE7 >> pFly->_RATE8 >> pFly->_RATE9 >> pFly->_RATE10;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_IDX] = pFly;
	}

	return true;
}


UpStoneGachyaResource::Flyweight *
UpStoneGachyaResource::GetFly(UpStoneGachyaType eType)
{
	int nType = static_cast<int>(eType);

	auto iter = clsFlyTree.find(nType);
	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}

bool
UpStoneGachyaResource::GetUpStoneGachyaQuality(UpStoneGachyaType eType, int & upstoneQuality)
{
	Flyweight * pFly = this->GetFly(eType);
	if (NULL == pFly)
	{
		return false;
	}

	int quality = 0;
	int accRate = 0;
	int randRate = rand() % 1000;

	for (; quality < 10; quality++)
	{
		switch (quality)
		{
		case 0 : accRate += pFly->_RATE1; break;
		case 1 : accRate += pFly->_RATE2; break;
		case 2 : accRate += pFly->_RATE3; break;
		case 3 : accRate += pFly->_RATE4; break;
		case 4 : accRate += pFly->_RATE5; break;
		case 5 : accRate += pFly->_RATE6; break;
		case 6 : accRate += pFly->_RATE7; break;
		case 7 : accRate += pFly->_RATE8; break;
		case 8 : accRate += pFly->_RATE9; break;
		case 9 : accRate += pFly->_RATE10; break;
		}

		if (randRate < accRate)
		{
			upstoneQuality = quality;
			return true;
		}
	}

	return false;
}

} /*NResource*/ } /*ProjectZ*/


